//
//  TopicleWebViewController.m
//  yigou
//
//  Created by SunChao on 17/1/23.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "TopicleWebViewController.h"
#import "YXCustomActionSheet.h"
#import "DyShare.h"
#import "SZTextView.h"
#import "TribeDetailViewController.h"
#import <IQKeyboardManager.h>
@interface TopicleWebViewController () <UIWebViewDelegate, YXCustomActionSheetDelegate>
{
    UIActivityIndicatorView *activityIndicatorView;
    UIView *opaqueView;
}

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIView *bottombar;
@property (strong, nonatomic) SZTextView* contentTextView;

@property (strong, nonatomic) UIImage *shareImg;

@property (assign, nonatomic) BOOL ISCOL;

@end

@implementation TopicleWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBack:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonShare.frame = CGRectMake(0, 0, 26, 20);
    [buttonShare setBackgroundImage:[UIImage imageNamed:@"goodshare"] forState:UIControlStateNormal];
    UIBarButtonItem *btnShare = [[UIBarButtonItem alloc]initWithCustomView:buttonShare];
    [buttonShare addTarget:self action:@selector(clickShare:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnShare;
    
    [self makeBottomBar];
    [self getDetail];
}

- (void)makeBottomBar {
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    line.backgroundColor = LineColor;
    [self.bottombar addSubview:line];
    
    UIView *border = [[UIView alloc] initWithFrame:CGRectMake(10, 10, ScreenWidth - 20, 30)];
    border.layer.masksToBounds = YES;
    border.layer.cornerRadius = 4.f;
    [border.layer setBorderWidth:1];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace, (CGFloat[]){0.9, 0.9, 0.9, 1});
    [border.layer setBorderColor:colorref];
    CGColorRelease(colorref);
    CGColorSpaceRelease(colorSpace);
    [self.bottombar addSubview:border];
    
    self.contentTextView = [[SZTextView alloc] init];
    self.contentTextView.frame = CGRectMake(0, 0, ScreenWidth - 20 - 50 - 10, 30);
    self.contentTextView.font = [UIFont systemFontOfSize:14];
    self.contentTextView.placeholder = @"说点什么";
    [border addSubview:self.contentTextView];
    //self.contentTextView.delegate = self;
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth - 20 - 50 - 1, 5, 1, 20)];
    line2.backgroundColor = LineColor;
    [border addSubview:line2];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(ScreenWidth - 20 - 50, 0, 50, 30);
    [button setTitle:@"评论" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button setTitleColor:[UIColor colorWithHexString:@"3b3b3b"] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor whiteColor];
    [border addSubview:button];
    [button addTarget:self action:@selector(clickComment:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)clickComment:(UIButton *)button {
    [self.view endEditing:YES];
    if (self.contentTextView.text.length == 0) {
        [ViewFactory showInfoMsg:@"请先输入内容！"];
        return;
    }
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU, self.articleContent, self.contentTextView.text];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        self.contentTextView.text = @"";
        [self.webView reload];
        [ViewFactory showSuccess:@"评论成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"评论失败！"];
    } failure:^(YTKBaseRequest *request) {
    }];
}

- (void)getDetail {
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/getIsCollectByContentId?content_id=%@", APIYIGOU, self.articleContent];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSNumber *col = [dict objectForKey:@"data"];
        self.ISCOL = [col boolValue];
        DYLog(@"");
    } error:^(YTKBaseRequest *request) {
    } failure:^(YTKBaseRequest *request) {
    }];
}

- (void)requestQuXiaoShouCang{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/delCollect?becollect_id=%@",APIYIGOU, self.articleContent];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.ISCOL = NO;
        [ViewFactory showSuccess:@"取消收藏成功"];
        
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}
- (void)requestShouCang{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *becollect_type = @"01";//01表示收藏内容
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/addCollect?becollect_id=%@&becollect_type=%@",APIYIGOU, self.articleContent,becollect_type];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.ISCOL = YES;
        [ViewFactory showSuccess:@"收藏成功"];
        
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}
- (void)clickCol {
    if(self.ISCOL) {
        [self requestQuXiaoShouCang];
    } else {
        [self requestShouCang];
    }
}

- (void)clickReport {
    DYBaseRequest *request = [DYBaseRequest new];
    //NSString *status = @"01";
    //report_obj举报对象，00：话题，01：文章，03：直播，04：商品
    //report_type举报类型,00：色情，01：反动，02：虚假，99：其他
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/addReport?report_obj=%@&report_obj_id=%@&report_type=%@&report_content=%@", APIYIGOU, @"00", self.articleContent, @"00", @""];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"举报成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"举报失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)downloadShareImage {
    if (!self.shareImg) {
        [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:self.shareimgurl] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            self.shareImg = image;
        }];
    }
}

- (void)clickShare:(UIButton *)button {
    YXCustomActionSheet *cusSheet = [[YXCustomActionSheet alloc] init];
    cusSheet.delegate = self;
    
    NSString *sctitle = @"收藏";
    NSString *scimg = @"sns_csc";
    if(self.ISCOL) {
        sctitle = @"取消收藏";
        scimg = @"sns_sc";
    }
    NSArray *contentArray = @[@{@"name":@"朋友圈",@"icon":@"sns_pyq"},
                              @{@"name":@"微信",@"icon":@"sns_wx"},
                              @{@"name":@"新浪微博",@"icon":@"sns_wb"},
                              @{@"name":@"QQ ",@"icon":@"sns_qq"},
                              @{@"name":@"QQ空间 ",@"icon":@"sns_qzone"},
                              @{@"name":sctitle,@"icon":scimg},
                              @{@"name":@"举报",@"icon":@"sns_jb"}];
    
    [cusSheet showInView:[UIApplication sharedApplication].keyWindow contentArray:contentArray];
}

- (void)customActionSheetButtonClick:(YXActionSheetButton *)btn {
    NSLog(@"第%li个按钮被点击了",(long)btn.tag);
    NSInteger index = btn.tag;
    
    DyShareType type;
    switch (index) {
        case 0:
            type = DyShareTypePengYouQuan;
            break;
        case 4:
            type = DyShareTypeQZone;
            break;
        case 2:
            type = DyShareTypeWeiBo;
            break;
        case 1:
            type = DyShareTypeWeiXin;
            break;
        case 3:
            type = DyShareTypeQQ;
            break;
        case 5: {
            [self clickCol];
            return;
        }
        case 6: {
            [self clickReport];
            return;
        }
        default:
            break;
    }
    [[DyShare getInstance]shareWithShareType:type Content:self.sharetitle title:self.sharetitle url:self.shareurl image:self.shareImg delegate:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationWhite:self];
    
    [self.webView setUserInteractionEnabled:YES];//是否支持交互
    self.webView.delegate=self;
    [self.webView setScalesPageToFit:YES];//自动缩放以适应屏幕
    //NSString *baseUrlString = [NSString stringWithFormat:@"%@/h5/mobile/#/topic_detail",@"https://app.zallhy.com"];

    //NSString *urlString = [NSString stringWithFormat:@"%@/%@/%@",baseUrlString,self.articleContent,[UserData usertoken]];
    //NSString *urlString = @"http://192.168.1.121:8080/#/article_detail/817279774781394944/uid:0";
    //NSString *urlString = @"http://192.168.1.121:8080/#/topic_detail/817279774781394944/uid:821597928173953024";
    //NSString *urlString = [NSString stringWithFormat:@"%@/h5/mobile/#/topic_detail/%@/uid:%@",APIYIGOU,self.articleContent ,[UserData userid]];
    //@"http://192.168.1.19"
    NSString *urlString = [NSString stringWithFormat:@"%@/h5/mobile/#/topic_detail/%@/uid:%@",APIYIGOU,self.articleContent ,[UserData userid]];
    NSURL *url = [NSURL URLWithString:urlString];
    [self.webView loadRequest:[ NSURLRequest requestWithURL: url]];
    
    [self downloadShareImage];
     [IQKeyboardManager sharedManager].enable = YES;
}
-(void)viewWillDisappear:(BOOL)animated
{
     [IQKeyboardManager sharedManager].enable = NO;
}
- (void)goPop {
    [ViewFactory dismissLoading];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goToLike:(NSString *)data {
    if ([data isEqualToString:@"0"]) {
        [self oc_praise:@"01"];
    } else {
        [self oc_praise:@"00"];
    }
}

- (void)getFocus:(NSString *)data {
    if ([data isEqualToString:@"0"]) {
        [self oc_cancleSubone];
    } else {
        [self oc_subone];
    }
}

- (void)joinTribe {
    [self oc_joinTribe];
}

- (void)goToTribe {
    TribeDetailViewController *tribe = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
    tribe.tribeID = self.articleTribeId;
    [self.navigationController pushViewController:tribe animated:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    
    //OC调用JS是基于协议拦截实现的 下面是相关操作
    NSString *absolutePath = request.URL.absoluteString;
    
    NSString *scheme = @"rrcc://";
    
    if ([absolutePath hasPrefix:scheme]) {
        NSString *subPath = [absolutePath substringFromIndex:scheme.length];
        
        if ([subPath containsString:@"?"]) {//1个或多个参数
            
            if ([subPath containsString:@"&"]) {//多个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                NSArray *params = [parameter componentsSeparatedByString:@"&"];
                
                if (params.count == 2) {
                    if ([self respondsToSelector:sel]) {
                        [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
                    }
                }
                
                
            } else {//1个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                
                if ([self respondsToSelector:sel]) {
                    [self performSelector:sel withObject:parameter];
                }
                
            }
            
        } else {//没有参数
            NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            SEL sel = NSSelectorFromString(methodName);
            
            if ([self respondsToSelector:sel]) {
                [self performSelector:sel];
            }
        }
    }
    
    return YES;
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
    [ViewFactory showLoadingEnableTouch];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    [ViewFactory dismissLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if (error) {
        NSDictionary *userinfo = error.userInfo;
        if (userinfo) {
            NSString *url = [userinfo objectForKey:@"NSErrorFailingURLStringKey"];
            if([url hasPrefix:@"rrcc://"]) {
                return;
            } else {
                DYLog(@"go this!");
            }
        }
    }
    [ViewFactory showErrorStrMsg:@"加载失败！"];
}

- (void)oc_subone {
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/setConcern?follow_obj_id=%@", APIYIGOU, self.articleUserId];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [self.webView stringByEvaluatingJavaScriptFromString:@"callback_focus('1')"];
        [ViewFactory showSuccess:@"关注成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"关注失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)oc_cancleSubone {
    NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/qxAttountByUserId?follow_obj_type=00&follow_obj_id=%@",APIYIGOU,self.articleUserId];
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [self.webView stringByEvaluatingJavaScriptFromString:@"callback_focus('0')"];
        [ViewFactory showSuccess:@"已取消关注！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"操作失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)oc_joinTribe {
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/joinTribe?tribe_id=%@", APIYIGOU, self.articleTribeId];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [self.webView stringByEvaluatingJavaScriptFromString:@"callback_joinTribe()"];
        [ViewFactory showSuccess:@"加入成功"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"加入失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)oc_praise:(NSString *)status {
    DYBaseRequest *request = [DYBaseRequest new];
    //NSString *status = @"01";
    
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/setContentLike?content_id=%@&status=%@", APIYIGOU, self.articleContent,status];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    request.ignoreCache = YES;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        if ([status isEqualToString:@"00"]) {
            [self.webView stringByEvaluatingJavaScriptFromString:@"callback_like('1')"];
            [ViewFactory showSuccess:@"点赞成功！"];
        } else {
            [self.webView stringByEvaluatingJavaScriptFromString:@"callback_like('0')"];
            [ViewFactory showSuccess:@"取消点赞！"];
        }
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"操作失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];    
}

@end
